/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Config.java
 *
 * Created on Apr 28, 2011, 3:01:59 AM
 */

package c0907m.group2.aitsm.gui;

import c0907m.group2.aitsm.gui.component.StatusBar;
import c0907m.group2.aitsm.gui.handler.ServerConnectedEvent;
import c0907m.group2.aitsm.gui.handler.ServerConnectedListener;
import c0907m.group2.aitsm.util.Helper;
import c0907m.group2.aitsm.util.Settings;

import javax.swing.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author ISTC
 */
public class Config extends JPanel {
    //default state on status bar when init
    private StatusBar statusBar;
    public static final String DEFAULT_STATUS = "Configure server connection";
    public final Logger logger = Logger.getLogger(Config.class.getName());
    public static Connection connection;

    public JButton getDefaultButton() {
        return btnConnect;
    }

    public void setStatusBar(StatusBar sb) {
        this.statusBar = sb;
    }

    /**
     * Creates new form Config
     */
    public Config() {
        initComponents();
        statusBar = new StatusBar();
        checkSettings();
    }

    /**
     * Register for ServerConnectedEvent
     *
     * @param l a listener of ServerConnectedEvent
     */
    public void addServerConnectedListener(ServerConnectedListener l) {
        listenerList.add(ServerConnectedListener.class, l);
    }

    /**
     * Unregister for ServerConnectedEvent
     *
     * @param l a listener of ServerConnectedEvent
     */
    public void removeServerConnectedListener(ServerConnectedListener l) {
        listenerList.remove(ServerConnectedListener.class, l);
    }

    /**
     * Fire a ServerConnectedEvent
     *
     * @param evt a fired ServerConnectedEvent
     */
    private void fireServerConnectedEvent(ServerConnectedEvent evt) {
        Object[] listeners = listenerList.getListenerList();

        for (int i = 0; i < listeners.length; i += 2) {
            if (listeners[i] == ServerConnectedListener.class) {
                ((ServerConnectedListener) listeners[i + 1]).serverConnected(evt);
            }
        }
    }

    /**
     * Check user's previous settings
     */
    private void checkSettings() {
        if (Integer.parseInt(Helper.PROPS.getProperty("connectionInfoSave")) == 1) {
            txtIp.setText(Helper.PROPS.getProperty("host"));
            txtPort.setText(Helper.PROPS.getProperty("port"));
            txtDatabase.setText(Helper.PROPS.getProperty("database"));
            txtUser.setText(Helper.PROPS.getProperty("user"));
            jpfPassword.setText(Helper.PROPS.getProperty("password"));
        }
    }


    /**
     * Connect to database
     */
    private void doConnect() {
        String host = txtIp.getText();
        String port = txtPort.getText();
        String db = txtDatabase.getText();
        String user = txtUser.getText();
        String password = String.copyValueOf(jpfPassword.getPassword());
        Helper.PROPS.setProperty("host", host);
        Helper.PROPS.setProperty("port", port);
        Helper.PROPS.setProperty("database", db);
        Helper.PROPS.setProperty("user", user);
        Helper.PROPS.setProperty("password", password);

        try {
            connection = Helper.getConnection();
            Main.popUpConfig.dispose();
            statusBar.setMessage("Successfully connected to server.", StatusBar.MESSAGE_TYPE);

            if (cbSaveConfig.isSelected()) {
                Helper.saveSettings();
            } else {
                Helper.PROPS.setProperty("connectionSave", "0");
                Helper.saveSettings();
            }
            fireServerConnectedEvent(new ServerConnectedEvent(this));
        } catch (SQLException e) {
            logger.log(Level.SEVERE, null, e);
            statusBar.setMessage("Failed to connect to database.", StatusBar.ERROR_TYPE);
        } catch (Exception e) {
            logger.log(Level.SEVERE, null, e);
            statusBar.setMessage("Unknown.", StatusBar.ERROR_TYPE);
        }
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dlgLogin = new JDialog();
        jLabel1 = new JLabel();
        jLabel2 = new JLabel();
        jLabel3 = new JLabel();
        txtIp = new JTextField();
        jLabel4 = new JLabel();
        txtUser = new JTextField();
        jLabel5 = new JLabel();
        jpfPassword = new JPasswordField();
        jLabel6 = new JLabel();
        txtPort = new JTextField();
        jLabel7 = new JLabel();
        txtDatabase = new JTextField();
        btnConnect = new JButton();
        cbSaveConfig = new JCheckBox();

        GroupLayout dlgLoginLayout = new GroupLayout(dlgLogin.getContentPane());
        dlgLogin.getContentPane().setLayout(dlgLoginLayout);
        dlgLoginLayout.setHorizontalGroup(
                dlgLoginLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGap(0, 522, Short.MAX_VALUE)
        );
        dlgLoginLayout.setVerticalGroup(
                dlgLoginLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGap(0, 179, Short.MAX_VALUE)
        );

        setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setIcon(new ImageIcon(Settings.IMAGES_DIR + "/config.png"));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel2.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel2.setText("Server config");

        jLabel3.setText("IP:");

        jLabel4.setText("Username:");

        jLabel5.setText("Password:");

        jLabel6.setText("Port:");

        txtPort.setText("1433");

        jLabel7.setText("Database:");

        txtDatabase.setText("AITSM");

        btnConnect.setText("Connect");
        btnConnect.setMaximumSize(new java.awt.Dimension(65, 23));
        btnConnect.setMinimumSize(new java.awt.Dimension(65, 23));
        btnConnect.setPreferredSize(new java.awt.Dimension(65, 23));
        btnConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConnectActionPerformed(evt);
            }
        });

        cbSaveConfig.setBackground(new java.awt.Color(255, 255, 255));
        cbSaveConfig.setSelected(true);
        cbSaveConfig.setText("Save configuration for next connections");

        GroupLayout layout = new GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(119, 119, 119)
                                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                        .addComponent(cbSaveConfig)
                                        .addComponent(btnConnect, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(64, Short.MAX_VALUE))
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                        .addContainerGap()
                                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                                .addGroup(layout.createSequentialGroup()
                                                        .addComponent(jLabel1)
                                                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                                                .addComponent(jLabel3)
                                                                .addComponent(jLabel6)
                                                                .addComponent(jLabel5)
                                                                .addComponent(jLabel7)
                                                                .addComponent(jLabel4))
                                                        .addGap(50, 50, 50)
                                                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                                                .addComponent(txtDatabase, GroupLayout.PREFERRED_SIZE, 271, GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(txtPort, GroupLayout.PREFERRED_SIZE, 271, GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(txtUser, GroupLayout.PREFERRED_SIZE, 271, GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(jpfPassword, GroupLayout.PREFERRED_SIZE, 271, GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(txtIp, GroupLayout.PREFERRED_SIZE, 271, GroupLayout.PREFERRED_SIZE)))
                                                .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                                        .addComponent(jLabel2, GroupLayout.PREFERRED_SIZE, 186, GroupLayout.PREFERRED_SIZE)
                                                        .addGap(36, 36, 36)))
                                        .addGap(11, 11, 11)))
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap(223, Short.MAX_VALUE)
                                .addComponent(cbSaveConfig)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnConnect, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
                                .addGap(22, 22, 22))
                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                        .addGap(39, 39, 39)
                                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                                .addComponent(jLabel1)
                                                .addGroup(layout.createSequentialGroup()
                                                        .addComponent(jLabel2)
                                                        .addGap(18, 18, 18)
                                                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                                .addComponent(txtIp, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(jLabel3))
                                                        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                                .addComponent(txtUser, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(jLabel4))
                                                        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                                .addComponent(jpfPassword, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(jLabel5))
                                                        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                                .addComponent(txtPort, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(jLabel6))
                                                        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                                                        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                                                .addComponent(txtDatabase, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                                                .addComponent(jLabel7))))
                                        .addContainerGap(82, Short.MAX_VALUE)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed
        statusBar.setMessage("Connecting to server...", StatusBar.MESSAGE_TYPE);
        doConnect();
    }//GEN-LAST:event_btnConnectActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private JButton btnConnect;
    private JCheckBox cbSaveConfig;
    private JDialog dlgLogin;
    private JLabel jLabel1;
    private JLabel jLabel2;
    private JLabel jLabel3;
    private JLabel jLabel4;
    private JLabel jLabel5;
    private JLabel jLabel6;
    private JLabel jLabel7;
    private JPasswordField jpfPassword;
    private JTextField txtDatabase;
    private JTextField txtIp;
    private JTextField txtPort;
    private JTextField txtUser;
    // End of variables declaration//GEN-END:variables

}
